#ifndef CAMERAMANAGER_H
#define CAMERAMANAGER_H

#include <QObject>
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QCameraInfo>
#include <QLabel>
#include <QTimer>
#include <QPixmap>
#include <QVideoFrame>
#include <QAbstractVideoSurface>
#include <QVideoSurfaceFormat>

class VideoSurface;

class CameraManager : public QObject
{
    Q_OBJECT

public:
    explicit CameraManager(QObject *parent = nullptr);
    ~CameraManager();

    // 摄像头控制
    bool startCamera();
    void stopCamera();
    bool isActive() const;
    
    // 拍照功能
    void captureImage();
    
    // 设置显示标签
    void setDisplayLabel(QLabel *label);
    
    // 获取可用摄像头列表
    QStringList getAvailableCameras() const;
    
    // 设置摄像头
    bool setCamera(int index);
    
    // 获取摄像头状态信息
    QString getCameraStatus() const;
    QString getResolution() const;
    int getFrameRate() const;

signals:
    void cameraStatusChanged(bool active);
    void frameRateChanged(int fps);
    void errorOccurred(const QString &error);
    void imageCaptured(const QString &fileName);

private slots:
    void onCameraStateChanged(QCamera::State state);
    void onCameraStatusChanged(QCamera::Status status);
    void onCameraError(QCamera::Error error);
    void onImageCaptured(int id, const QImage &image);
    void onImageSaved(int id, const QString &fileName);
    void updateFrameRate();

private:
    void setupCamera();
    void setupImageCapture();
    QString getErrorString(QCamera::Error error) const;

private:
    QCamera *m_camera;
    QCameraImageCapture *m_imageCapture;
    VideoSurface *m_videoSurface;
    QLabel *m_displayLabel;
    QTimer *m_frameRateTimer;
    
    int m_frameCount;
    int m_currentFPS;
    bool m_isActive;
    QString m_lastError;
    QSize m_resolution;
};

// 自定义视频表面类，用于将摄像头画面显示到QLabel上
class VideoSurface : public QAbstractVideoSurface
{
    Q_OBJECT

public:
    explicit VideoSurface(QLabel *label, QObject *parent = nullptr);

    QList<QVideoFrame::PixelFormat> supportedPixelFormats(
        QAbstractVideoBuffer::HandleType handleType = QAbstractVideoBuffer::NoHandle) const override;

    bool present(const QVideoFrame &frame) override;

signals:
    void frameAvailable();

private:
    QImage convertYUYVToRGB(const QVideoFrame &frame);
    QImage convertUYVYToRGB(const QVideoFrame &frame);
    QImage convertNV12ToRGB(const QVideoFrame &frame);
    
    QLabel *m_targetLabel;
    QSize m_targetSize;
};

#endif // CAMERAMANAGER_H 